package com.hsy.leancloudchat

import cn.leancloud.im.v2.LCIMClient
import cn.leancloud.im.v2.LCIMConversation
import cn.leancloud.im.v2.LCIMConversationEventHandler
import cn.leancloud.im.v2.LCIMMessage
import cn.leancloud.im.v2.LCIMMessageHandler
import cn.leancloud.im.v2.LCIMMessageManager

class CustomIMEventHandler {
    companion object {
        init {
            LCIMMessageManager.setConversationEventHandler(CustomConversationEventHandler())
            LCIMMessageManager.registerDefaultMessageHandler(CustomMessageHandler())
        }

        private var subscribers = mutableListOf<IIMEventSubscriber>()

        fun subscribe(subscriber: IIMEventSubscriber) {
            subscribers.add(subscriber)
        }

        fun unSubscribe(subscriber: IIMEventSubscriber) {
            subscribers.remove(subscriber)
        }

        private fun notifyOnInvited(
            client: LCIMClient?,
            conversation: LCIMConversation?,
            operator: String?
        ) {
            subscribers.forEach {
                it.onInvited(client, conversation, operator)
            }
        }

        private fun notifyOnMessage(
            message: LCIMMessage?,
            conversation: LCIMConversation?,
            client: LCIMClient?
        ) {
            subscribers.forEach {
                it.onMessage(message, conversation, client)
            }
        }
    }

    interface IIMEventSubscriber {
        fun onInvited(
            client: LCIMClient?,
            conversation: LCIMConversation?,
            operator: String?
        ) {
        }

        fun onMessage(
            message: LCIMMessage?,
            conversation: LCIMConversation?,
            client: LCIMClient?
        )
    }

    class CustomConversationEventHandler : LCIMConversationEventHandler() {
        override fun onInvited(
            client: LCIMClient?,
            conversation: LCIMConversation?,
            operator: String?
        ) {
            notifyOnInvited(client, conversation, operator)
        }

        override fun onMemberLeft(
            client: LCIMClient?,
            conversation: LCIMConversation?,
            members: MutableList<String>?,
            kickedBy: String?
        ) {
        }

        override fun onMemberJoined(
            client: LCIMClient?,
            conversation: LCIMConversation?,
            members: MutableList<String>?,
            invitedBy: String?
        ) {
        }

        override fun onKicked(
            client: LCIMClient?,
            conversation: LCIMConversation?,
            kickedBy: String?
        ) {
        }

    }

    class CustomMessageHandler : LCIMMessageHandler() {
        override fun onMessage(
            message: LCIMMessage?,
            conversation: LCIMConversation?,
            client: LCIMClient?
        ) {
            notifyOnMessage(message, conversation, client)
        }
    }
}